<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小红书笔记挖掘</title>
    <!-- TailwindCSS 3.x CDN -->
    <script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
    <!-- Preline UI -->
    <script src="https://unpkg.com/preline@2.0.3/dist/preline.js"></script>
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" crossorigin="anonymous" />
    <!-- SheetJS for Excel export -->
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <!-- Tailwind自定义主色/暗色 -->
    <script>
      tailwind.config = {
        darkMode: 'class',
        theme: {
          extend: {
            colors: {
              primary: '#ff2442',
              secondary: '#f5f5f5',
              dark: '#18181b',
              light: '#fff',
              gray: {
                100: '#f5f5f5',
                200: '#e5e7eb',
                300: '#d1d5db',
                400: '#9ca3af',
                500: '#6b7280',
                600: '#4b5563',
                700: '#374151',
                800: '#1f2937',
                900: '#111827',
              },
            },
            fontFamily: {
              sans: [
                '-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Open Sans', 'Helvetica Neue', 'sans-serif'
              ]
            }
          }
        }
      }
    </script>
    <style>
      html {
        scroll-behavior: smooth;
      }
      .fade-in {
        animation: fadeIn 0.7s ease;
      }
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(16px); }
        to { opacity: 1; transform: none; }
      }
    </style>
</head>
<body class="bg-secondary dark:bg-dark min-h-screen font-sans transition-colors duration-300">
  <!-- 顶部Logo与副标题 -->
  <header class="w-full py-8 flex flex-col items-center fade-in">
    <div class="flex items-center gap-3">
      <span class="text-primary text-3xl font-bold"><i class="fa-solid fa-book-open"></i></span>
      <h1 class="text-2xl md:text-3xl font-extrabold text-primary tracking-tight">小红书笔记挖掘</h1>
    </div>
    <p class="mt-2 text-gray-500 dark:text-gray-400 text-sm md:text-base">批量下载小红书笔记、评论，挖掘小红书关键词，低粉爆款笔记</p>
    <!-- 深浅色切换 -->
    <button id="toggleDark" class="absolute right-4 top-4 p-2 rounded-full bg-gray-100 dark:bg-gray-800 hover:scale-110 transition" title="切换深浅色">
      <i id="themeIcon" class="fa-solid fa-moon text-gray-600 dark:text-yellow-300"></i>
    </button>
  </header>

  <!-- 下载插件提示条 -->
  <div class="w-full py-3 px-4 mb-6 fade-in">
    <div class="max-w-4xl mx-auto px-2 md:px-0 flex flex-col gap-4">
      <!-- 简洁提示和按钮 -->
      <div class="flex flex-col md:flex-row items-center justify-between gap-3">
        <div class="flex items-center gap-3">
          <i class="fa-solid fa-download text-primary text-xl"></i>
          <div class="text-gray-700 dark:text-gray-200">
            <span class="font-semibold">还没有安装插件？</span>
            <span class="text-sm ml-2">立即下载小红书笔记挖掘插件，开启数据挖掘之旅</span>
          </div>
        </div>
        <a href="./release.html" 
           target="_blank" 
           class="bg-primary hover:bg-red-600 text-white font-semibold px-6 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2 whitespace-nowrap">
          <i class="fa-solid fa-arrow-up-right-from-square"></i> 前往下载
        </a>
      </div>
      <!-- 详细补充提示语 -->
      <!-- <div id="detailedTipsContainer" class="text-gray-700 dark:text-gray-200 text-sm leading-relaxed border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
        <p class="font-semibold">重要提示：<button id="toggleDetailedTips" class="ml-2 text-primary text-xs font-normal hover:underline focus:outline-none">展开</button></p>
        <div id="detailedTipsContent" class="hidden">
          <p>首次使用，需安装对应浏览器插件，暂不支持移动端使用，<a href="./release.html" target="_blank" class="text-primary hover:underline font-bold">点击此处下载：小红助手插件</a></p>
          <p class="mt-1">下载后，根据提示授予权限，并重新刷新本页面。</p>
          <p class="mt-1">如果你从未在你的浏览器上登录过小红书，请先完成登录。</p>
          <p class="mt-1">获取笔记时浏览器会自动打开小红书网页，请勿慌张，也无需操作，完成后会自动关闭。</p>
          <p class="mt-1">此功能仅在 Chrome 或兼容的浏览器中有效。</p>
        </div>
      </div> -->
    </div>
  </div>

  <main class="max-w-4xl mx-auto px-2 md:px-0 fade-in">
    <!-- Tab切换区 -->
    <div class="mb-6">
      <ul class="hs-tabs nav nav-tabs flex flex-wrap text-sm font-medium text-center text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700" role="tablist">
        <li class="me-2" role="presentation">
          <button class="hs-tab-active:bg-primary hs-tab-active:text-white inline-block p-4 rounded-t-lg hover:text-primary transition" id="tab-keyword" data-hs-tab="#tab-panel-keyword" type="button" role="tab" aria-controls="tab-panel-keyword" aria-selected="true"><i class="fa-solid fa-key"></i> 关键词</button>
        </li>
        <li class="me-2" role="presentation">
          <button class="hs-tab-active:bg-primary hs-tab-active:text-white inline-block p-4 rounded-t-lg hover:text-primary transition" id="tab-feed" data-hs-tab="#tab-panel-feed" type="button" role="tab" aria-controls="tab-panel-feed" aria-selected="false"><i class="fa-solid fa-layer-group"></i> 频道笔记</button>
        </li>
        <li class="me-2" role="presentation">
          <button class="hs-tab-active:bg-primary hs-tab-active:text-white inline-block p-4 rounded-t-lg hover:text-primary transition" id="tab-user" data-hs-tab="#tab-panel-user" type="button" role="tab" aria-controls="tab-panel-user" aria-selected="false"><i class="fa-solid fa-user"></i> 用户笔记</button>
        </li>
        <li role="presentation">
          <button class="hs-tab-active:bg-primary hs-tab-active:text-white inline-block p-4 rounded-t-lg hover:text-primary transition" id="tab-comment" data-hs-tab="#tab-panel-comment" type="button" role="tab" aria-controls="tab-panel-comment" aria-selected="false"><i class="fa-solid fa-comments"></i> 评论挖掘</button>
        </li>
      </ul>
    </div>

    <!-- Tab内容区 -->
    <div class="relative bg-white dark:bg-gray-900 rounded-xl shadow p-6 fade-in">
      <!-- 关键词Tab -->
      <div id="tab-panel-keyword" class="hs-tab-content" role="tabpanel" aria-labelledby="tab-keyword">
        <!-- 搜索表单 -->
        <form class="flex flex-col md:flex-row gap-4 items-center mb-4" onsubmit="return false;">
          <input type="text" id="searchKeyword" class="flex-1 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" placeholder="输入关键词，如 英国" oninput="updateSearchUrl()">
          <input type="number" id="noteCount" class="w-32 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" min="1" max="500" value="10" title="笔记数量">
          <button id="testSearchExtraction" class="bg-primary hover:bg-red-600 text-white font-semibold px-6 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2" type="button"><i class="fa-solid fa-magnifying-glass"></i> 获取笔记</button>
        </form>
        <input type="text" id="searchUrl" class="w-full mb-2 px-4 py-2 rounded border border-gray-200 bg-gray-50 text-gray-500 text-xs dark:bg-gray-800 dark:border-gray-700" placeholder="https://www.xiaohongshu.com/search_result?keyword=xxx" readonly>
        <!-- 相关搜索词Tag区 -->
        <div class="mb-4">
          <div class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">大家都在搜</div>
          <div id="relatedSearches" class="flex flex-wrap gap-2"></div>
        </div>
        <!-- 长尾词展示区 -->
        <div class="mb-4">
          <div class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">长尾词</div>
          <div id="longTailKeywords" class="flex flex-wrap gap-2"></div>
        </div>
        <!-- 笔记表格区 -->
        <div class="overflow-x-auto">
          <table class="min-w-full text-sm text-left text-gray-700 dark:text-gray-200 border rounded-xl shadow-sm">
            <thead class="bg-gray-100 dark:bg-gray-800">
              <tr>
                <th class="px-4 py-2">标题</th>
                <th class="px-4 py-2">作者</th>
                <th class="px-4 py-2">点赞</th>
                <th class="px-4 py-2">发布时间</th>
                <th class="px-4 py-2">操作</th>
              </tr>
            </thead>
            <tbody id="noteTableBody" class="bg-white dark:bg-gray-900">
              <!-- 动态填充 -->
            </tbody>
          </table>
        </div>
        <div class="flex justify-between items-center mt-4">
          <span class="text-gray-400 text-xs" id="noteCountInfo"></span>
          <button id="downloadExcel" class="bg-green-500 hover:bg-green-600 text-white font-semibold px-4 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2"><i class="fa-solid fa-file-excel"></i> 下载Excel</button>
        </div>
      </div>
      <!-- 频道笔记Tab（原型稿风格） -->
      <div id="tab-panel-feed" class="hs-tab-content hidden" role="tabpanel" aria-labelledby="tab-feed">
        <form class="bg-white dark:bg-gray-900 p-6 rounded-xl shadow flex flex-col gap-4 mb-6" onsubmit="return false;">
          <div class="flex flex-col md:flex-row md:items-center gap-4">
            <div class="flex-1 min-w-0">
              <label class="block text-gray-700 dark:text-gray-300 font-semibold mb-1" for="feedChannelSelect">选择频道</label>
              <select id="feedChannelSelect" class="w-full px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white">
                <option value="homefeed.fashion_v3">穿搭</option>
                <option value="homefeed.food_v3">美食</option>
                <option value="homefeed.cosmetics_v3">彩妆</option>
                <option value="homefeed.movie_and_tv_v3">影视</option>
                <option value="homefeed.career_v3">职场</option>
                <option value="homefeed.love_v3">情感</option>
                <option value="homefeed.household_product_v3">家居</option>
                <option value="homefeed.gaming_v3">游戏</option>
                <option value="homefeed.travel_v3">旅行</option>
                <option value="homefeed.fitness_v3">健身</option>
              </select>
            </div>
            <div>
              <label class="block text-gray-700 dark:text-gray-300 font-semibold mb-1" for="feedNoteCount">笔记数量 (最大500条)</label>
              <input type="number" id="feedNoteCount" class="w-32 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" min="1" max="500" value="10">
              <div class="text-xs text-gray-400 mt-1">最终笔记数量可能会略有出入</div>
            </div>
          </div>
          <button id="testExploreExtraction" class="w-full bg-primary hover:bg-red-600 text-white font-semibold px-6 py-2 rounded shadow transition-transform transform hover:scale-105 mt-2 flex items-center justify-center gap-2" type="button">
            <i class="fa-solid fa-layer-group"></i> 获取笔记
          </button>
        </form>
        <div class="relative">
          <button id="downloadFeedExcel" class="absolute right-0 -top-12 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 px-3 py-1 rounded shadow flex items-center gap-2 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800 transition">
            <i class="fa-solid fa-download"></i> 下载文件
          </button>
          <!-- Table View for Channel Notes (always present) -->
          <div class="overflow-x-auto mt-2">
            <table class="min-w-full text-sm text-left text-gray-700 dark:text-gray-200 border rounded-xl shadow-sm">
              <thead class="bg-gray-100 dark:bg-gray-800">
                <tr>
                  <th class="px-4 py-2">标题</th>
                  <th class="px-4 py-2">作者</th>
                  <th class="px-4 py-2">点赞</th>
                  <th class="px-4 py-2">发布时间</th>
                </tr>
              </thead>
              <tbody id="feedTableBody" class="bg-white dark:bg-gray-900">
                <!-- 动态填充 -->
              </tbody>
            </table>
          </div>
          <!-- Card View for Channel Notes (for real data) -->
          <div id="feedCardView" class="grid grid-cols-1 md:grid-cols-2 gap-4 bg-transparent mt-4">
            <!-- 动态填充 -->
          </div>
          <div class="text-gray-400 text-xs mt-2" id="feedCountInfo"></div>
        </div>
      </div>
      <!-- 用户笔记Tab -->
      <div id="tab-panel-user" class="hs-tab-content hidden" role="tabpanel" aria-labelledby="tab-user">
        <form class="flex flex-col md:flex-row gap-4 items-center mb-4" onsubmit="return false;">
          <input type="text" id="userUrl" class="flex-1 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" placeholder="输入用户主页URL">
          <input type="number" id="userNoteCount" class="w-32 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" min="1" max="500" value="10" title="笔记数量">
          <button id="testProfileExtraction" class="bg-primary hover:bg-red-600 text-white font-semibold px-6 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2" type="button"><i class="fa-solid fa-user"></i> 获取用户笔记</button>
        </form>
        <!-- 用户笔记表格区（复用noteTableBody） -->
        <div class="overflow-x-auto">
          <table class="min-w-full text-sm text-left text-gray-700 dark:text-gray-200 border rounded-xl shadow-sm">
            <thead class="bg-gray-100 dark:bg-gray-800">
              <tr>
                <th class="px-4 py-2">标题</th>
                <th class="px-4 py-2">作者</th>
                <th class="px-4 py-2">点赞</th>
                <th class="px-4 py-2">发布时间</th>
                <th class="px-4 py-2">操作</th>
              </tr>
            </thead>
            <tbody id="userTableBody" class="bg-white dark:bg-gray-900">
              <!-- 动态填充 -->
            </tbody>
          </table>
        </div>
        <div class="flex justify-between items-center mt-4">
          <span class="text-gray-400 text-xs" id="userCountInfo"></span>
          <button id="downloadUserExcel" class="bg-green-500 hover:bg-green-600 text-white font-semibold px-4 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2"><i class="fa-solid fa-file-excel"></i> 下载Excel</button>
        </div>
      </div>
      <!-- 评论挖掘Tab -->
      <div id="tab-panel-comment" class="hs-tab-content hidden" role="tabpanel" aria-labelledby="tab-comment">
        <form class="flex flex-col md:flex-row gap-4 items-center mb-4" onsubmit="return false;">
          <input type="text" id="noteUrl" class="flex-1 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" placeholder="输入笔记URL">
          <input type="number" id="commentCount" class="w-32 px-4 py-2 rounded border border-gray-300 focus:ring-2 focus:ring-primary focus:outline-none dark:bg-gray-800 dark:border-gray-700 dark:text-white" min="1" max="500" value="10" title="评论数量">
          <button id="testCommentExtraction" class="bg-primary hover:bg-red-600 text-white font-semibold px-6 py-2 rounded shadow transition-transform transform hover:scale-105 flex items-center gap-2" type="button"><i class="fa-solid fa-comments"></i> 获取评论</button>
        </form>
        <!-- 评论区 -->
        <div id="commentResult" class="mt-4"></div>
      </div>
    </div>

    <!-- 状态监控与日志区 -->
    <section class="mt-8 fade-in">
      <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2 mb-2">
        <div class="text-sm text-gray-500 dark:text-gray-400" id="status">等待操作...</div>
        <div class="flex items-center gap-2">
          <select id="mockType" class="px-2 py-1 rounded border border-gray-300 dark:bg-gray-800 dark:border-gray-700 dark:text-white">
            <option value="keywordnote">关键词笔记Mock</option>
            <option value="comment">评论Mock</option>
            <option value="usernote">用户笔记Mock</option>
            <option value="channelnote">频道笔记Mock</option>
          </select>
          <button id="testMockData" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded shadow transition-transform transform hover:scale-105"><i class="fa-solid fa-vial"></i> 测试模拟数据</button>
        </div>
      </div>
      <div id="logResult" class="bg-white dark:bg-gray-900 rounded-lg shadow p-4 max-h-48 overflow-y-auto text-xs"></div>
    </section>
  </main>

  <!-- 原有JS逻辑和美化适配脚本（详见注释） -->
  <script>
    // 配置对象 - 存储用户设置的参数
    let config = {
        targetNoteCount: 20,    // 目标笔记数量
        targetCommentCount: 20,  // 目标评论数量
        scrollPauseMs: 1000      // 滚动暂停时间（毫秒）
    };

    // 扩展ID - 用于与扩展通信
    const EXTENSION_ID = 'mlhkpmjljmpmnjldhhbikmfmbgkjddkn';

    // 发送消息到扩展的通用函数
    async function sendMessageToExtension(message) {
        console.log('待发送给chrome插件消息 | sendMessageToExtension', message);
        try {
            if (!EXTENSION_ID) {
                throw new Error('请先设置扩展ID');
            }

            // 检查扩展是否已安装
            if (!chrome.runtime) {
                throw new Error('Chrome API 不可用，请确保在Chrome浏览器中运行');
            }

            // 添加重试逻辑
            let retries = 3;
            let lastError = null;

            while (retries > 0) {
                try {
                    return await new Promise((resolve, reject) => {
                        chrome.runtime.sendMessage(EXTENSION_ID, message, response => {
                            if (chrome.runtime.lastError) {
                                reject(new Error(chrome.runtime.lastError.message));
                            } else {
                                resolve(response);
                            }
                        });
                    });
                } catch (error) {
                    lastError = error;
                    retries--;
                    if (retries > 0) {
                        console.log(`发送消息失败，剩余重试次数: ${retries}`);
                        await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
                    }
                }
            }

            throw lastError || new Error('发送消息失败');
        } catch (error) {
            console.error('发送消息失败:', error);
            updateStatus(`发送消息失败: ${error.message}`);
            throw error;
        }
    }

    // 自动更新搜索URL - 根据关键字生成搜索链接
    function updateSearchUrl() {
        const keyword = document.getElementById('searchKeyword').value;
        const searchUrl = `https://www.xiaohongshu.com/search_result?keyword=${encodeURIComponent(keyword)}`;
        document.getElementById('searchUrl').value = searchUrl;
    }

    // 测试搜索页提取按钮点击事件
    const testSearchBtn = document.getElementById('testSearchExtraction');
    if (testSearchBtn) {
      testSearchBtn.addEventListener('click', async () => {
        const urlInput = document.getElementById('searchUrl');
        const url = urlInput ? urlInput.value : '';
        if (!url) {
          updateStatus('请输入搜索URL');
          return;
        }
        updateStatus('开始提取搜索页数据...');
        try {
          const response = await sendMessageToExtension({
            action: 'searchXiaohongshu',
            query: new URL(url).searchParams.get('keyword'),
            targetCount: config.targetNoteCount,
            targetCommentCount: config.targetCommentCount
          });
          const noteResult = document.getElementById('noteResult');
          if (noteResult) noteResult.textContent = JSON.stringify(response, null, 2);
          updateStatus('搜索页数据提取完成');
        } catch (error) {
          updateStatus('提取失败: ' + error.message);
        }
      });
    }

    // 频道笔记Tab 获取数据
    const feedBtn = document.getElementById('testExploreExtraction');
    if(feedBtn){
      feedBtn.onclick = async () => {
        const channelSelect = document.getElementById('feedChannelSelect');
        const countInput = document.getElementById('feedNoteCount');
        const channel = channelSelect ? channelSelect.value : '';
        const count = countInput ? parseInt(countInput.value) : 0;
        updateStatus('开始提取频道笔记...');
        try {
          const response = await sendMessageToExtension({
            action: 'getChannelFeed',
            channel_id: channel,
            targetCount: count,
            targetCommentCount: config.targetCommentCount
          });
          renderFeedTable(response, 'feedTableBody', 'feedCountInfo');
          updateStatus('频道笔记提取完成', 'success');
        } catch (e) {
          updateStatus('提取失败: ' + e.message, 'error');
        }
      };
    }
    // 渲染频道笔记表格（无"操作"列）
    function renderFeedTable(data, tableBodyId, countInfoId, renderMode = 'card') {
      const tbody = document.getElementById(tableBodyId);
      const cardView = document.getElementById('feedCardView');

      if (!tbody || !cardView) return;

      tbody.innerHTML = ''; // Clear table body
      cardView.innerHTML = ''; // Clear card view

      if (!data || !data.notes || !Array.isArray(data.notes)) {
        // If no data, still show appropriate view based on mode or default
        if (renderMode === 'table' || renderMode === 'both') {
             tbody.parentElement.classList.remove('grid', 'grid-cols-1', 'md:grid-cols-2', 'gap-4', 'bg-transparent');
             tbody.parentElement.classList.add('overflow-x-auto');
             tbody.style.display = '';
             cardView.style.display = 'none';
             tbody.innerHTML = '<tr><td colspan="4" class="text-center text-gray-400 py-4">暂无笔记数据</td></tr>';
        } else { // 'card' mode or no specific mode, default to showing cards if that's the intended default empty state
             tbody.parentElement.classList.remove('overflow-x-auto');
             tbody.style.display = 'none';
             cardView.style.display = ''; // Ensure card view area is visible even if empty
             cardView.innerHTML = '<div class="text-center text-gray-400 py-4">暂无笔记数据</div>';
        }
         if (countInfoId) {
            document.getElementById(countInfoId).textContent = `共 0 条`;
          }
        return;
      }

      if (renderMode === 'table') {
        // Table Mode (for mock data)
        tbody.parentElement.classList.remove('grid', 'grid-cols-1', 'md:grid-cols-2', 'gap-4', 'bg-transparent');
        tbody.parentElement.classList.add('overflow-x-auto');
        tbody.style.display = ''; // Show table body
        cardView.style.display = 'none'; // Hide card view

        tbody.innerHTML = data.notes.map(note => `
          <tr>
            <td class="px-4 py-2 max-w-xs truncate">
              <a href="${note.url || '#'}" target="_blank" class="text-primary hover:underline">${note.title || 'N/A'}</a>
            </td>
            <td class="px-4 py-2 flex items-center gap-2">
              <img src="${note.authorAvatarUrl || ''}" alt="" class="w-6 h-6 rounded-full object-cover" loading="lazy">
              <span>${note.author || 'N/A'}</span>
            </td>
            <td class="px-4 py-2">${note.likeCount || 0}</td>
            <td class="px-4 py-2">${note.publishTime || 'N/A'}</td>
          </tr>
        `).join('');

      } else if (renderMode === 'card') {
        // Card Mode (for real data, originally only card view)
        tbody.parentElement.classList.remove('overflow-x-auto'); // Remove table overflow
        tbody.style.display = 'none'; // Hide table body
        cardView.style.display = ''; // Show card view

        cardView.innerHTML = data.notes.map(note => `
          <div class="bg-white dark:bg-gray-800 rounded-xl shadow flex flex-col md:flex-row gap-4 p-4 h-full">
            <a href="${note.url}" target="_blank" class="block flex-shrink-0">
              <img src="${note.imageUrl || ''}" class="w-28 h-28 object-cover rounded-lg border mb-2 md:mb-0" loading="lazy">
            </a>
            <div class="flex-1 flex flex-col justify-between">
              <div>
                <a href="${note.url}" target="_blank" class="font-bold text-lg text-gray-900 dark:text-gray-100 hover:text-primary line-clamp-2">${note.title || 'N/A'}</a>
                <div class="flex items-center gap-2 mt-2 mb-1">
                  <img src="${note.authorAvatarUrl || ''}" class="w-7 h-7 rounded-full object-cover border" loading="lazy">
                  <span class="text-sm text-gray-700 dark:text-gray-300">${note.author || 'N/A'}</span>
                </div>
              </div>
              <div class="flex items-center gap-4 mt-2">
                <span class="text-xs text-gray-500"><i class="fa-regular fa-heart"></i> ${note.likeCount || 0}</span>
                <span class="text-xs text-gray-400">${note.publishTime || ''}</span>
                <a href="${note.url}" target="_blank" class="ml-auto bg-primary text-white px-3 py-1 rounded shadow text-xs hover:bg-red-600 transition"><i class="fa-solid fa-arrow-up-right-from-square"></i> 查看</a>
              </div>
            </div>
          </div>
        `).join('');
      } else if (renderMode === 'both') {
         // Both Table and Card Mode (for real data when both are desired)
        tbody.parentElement.classList.add('overflow-x-auto'); // Keep table overflow
        tbody.style.display = ''; // Show table body
        cardView.style.display = ''; // Show card view

         // Render to Table
         tbody.innerHTML = data.notes.map(note => `
           <tr>
             <td class="px-4 py-2 max-w-xs truncate">
               <a href="${note.url || '#'}" target="_blank" class="text-primary hover:underline">${note.title || 'N/A'}</a>
             </td>
             <td class="px-4 py-2 flex items-center gap-2">
               <img src="${note.authorAvatarUrl || ''}" alt="" class="w-6 h-6 rounded-full object-cover" loading="lazy">
               <span>${note.author || 'N/A'}</span>
             </td>
             <td class="px-4 py-2">${note.likeCount || 0}</td>
             <td class="px-4 py-2">${note.publishTime || 'N/A'}</td>
           </tr>
         `).join('');

         // Render to Cards
        cardView.innerHTML = data.notes.map(note => `
          <div class="bg-white dark:bg-gray-800 rounded-xl shadow flex flex-col md:flex-row gap-4 p-4 h-full">
            <a href="${note.url}" target="_blank" class="block flex-shrink-0">
              <img src="${note.imageUrl || ''}" class="w-28 h-28 object-cover rounded-lg border mb-2 md:mb-0" loading="lazy">
            </a>
            <div class="flex-1 flex flex-col justify-between">
              <div>
                <a href="${note.url}" target="_blank" class="font-bold text-lg text-gray-900 dark:text-gray-100 hover:text-primary line-clamp-2">${note.title || 'N/A'}</a>
                <div class="flex items-center gap-2 mt-2 mb-1">
                  <img src="${note.authorAvatarUrl || ''}" class="w-7 h-7 rounded-full object-cover border" loading="lazy">
                  <span class="text-sm text-gray-700 dark:text-gray-300">${note.author || 'N/A'}</span>
                </div>
              </div>
              <div class="flex items-center gap-4 mt-2">
                <span class="text-xs text-gray-500"><i class="fa-regular fa-heart"></i> ${note.likeCount || 0}</span>
                <span class="text-xs text-gray-400">${note.publishTime || ''}</span>
                <a href="${note.url}" target="_blank" class="ml-auto bg-primary text-white px-3 py-1 rounded shadow text-xs hover:bg-red-600 transition"><i class="fa-solid fa-arrow-up-right-from-square"></i> 查看</a>
              </div>
            </div>
          </div>
        `).join('');

      }

      if (countInfoId) {
        document.getElementById(countInfoId).textContent = `共 ${data.notes.length} 条`;
      }
    }
    // 频道笔记Tab下载
    const feedDownloadBtn = document.getElementById('downloadFeedExcel');
    if(feedDownloadBtn){
      feedDownloadBtn.onclick = () => exportTableToExcel('feedTableBody', '频道笔记.xlsx');
    }
    // 新增：关键词Tab下载
    const keywordDownloadBtn = document.getElementById('downloadExcel');
    if(keywordDownloadBtn){
      keywordDownloadBtn.onclick = () => exportTableToExcel('noteTableBody', '关键词笔记.xlsx');
    }
    // 新增：用户笔记Tab下载
    const userDownloadBtn = document.getElementById('downloadUserExcel');
    if(userDownloadBtn){
      userDownloadBtn.onclick = () => exportTableToExcel('userTableBody', '用户笔记.xlsx');
    }

    // 实现表格导出为Excel的函数
    function exportTableToExcel(tableBodyId, filename) {
      const tableBody = document.getElementById(tableBodyId);
      if (!tableBody) return;
      // 获取thead
      const table = tableBody.closest('table');
      if (!table) return;

      // 创建一个新的表格用于导出
      const exportTable = document.createElement('table');
      // 复制表头
      const thead = table.querySelector('thead').cloneNode(true);
      exportTable.appendChild(thead);
      
      // 创建tbody
      const tbody = document.createElement('tbody');
      // 遍历原始表格的行
      tableBody.querySelectorAll('tr').forEach(row => {
        const newRow = document.createElement('tr');
        // 复制每个单元格，但处理最后一列（操作列）
        row.querySelectorAll('td').forEach((cell, index) => {
          const newCell = document.createElement('td');
          if (index === row.cells.length - 1) {
            // 最后一列，获取链接而不是文本
            const link = cell.querySelector('a');
            if (link) {
              newCell.textContent = link.href;
            }
          } else {
            // 其他列直接复制内容
            newCell.textContent = cell.textContent;
          }
          newRow.appendChild(newCell);
        });
        tbody.appendChild(newRow);
      });
      exportTable.appendChild(tbody);

      // 使用SheetJS导出
      const wb = XLSX.utils.table_to_book(exportTable, {sheet: 'Sheet1'});
      XLSX.writeFile(wb, filename);
    }

    // 用户信息卡片渲染（原型风格）
    function renderUserProfileCard(profile, containerId = 'userProfileCard') {
      let container = document.getElementById(containerId);
      if (!container) {
        // 若不存在则自动插入到用户笔记Tab顶部
        const userTab = document.getElementById('tab-panel-user');
        if (!userTab) return;
        container = document.createElement('div');
        container.id = containerId;
        userTab.insertBefore(container, userTab.children[1]);
      }
      if (!profile) {
        container.innerHTML = '';
        return;
      }
      container.innerHTML = `
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-4 flex flex-col md:flex-row gap-4 items-center">
          <img src="${profile.avatarUrl || ''}" class="w-16 h-16 rounded-full object-cover border-2 border-primary" loading="lazy">
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-1">
              <span class="text-lg font-bold">${profile.nickname || ''}</span>
              ${profile.ipLocation ? `<span class='text-xs bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded'>${profile.ipLocation}</span>` : ''}
            </div>
            <div class="text-gray-500 dark:text-gray-300 text-sm mb-2">${(profile.description || '').replace(/\n/g, '<br>')}</div>
            <div class="flex gap-6 text-sm text-gray-600 dark:text-gray-400">
              <span>关注 <b>${profile.followsCount || 0}</b></span>
              <span>粉丝 <b>${profile.fansCount || 0}</b></span>
              <span>获赞与收藏 <b>${profile.likesAndCollectsCount || 0}</b></span>
            </div>
          </div>
        </div>
      `;
    }

    // 动态加载json文件
    async function loadMockJson(type) {
        let file;
        switch(type) {
            case 'keywordnote':
                file = 'mock/keyword_note.json';
                break;
            case 'comment':
                file = 'mock/resp_comment.json';
                break;
            case 'usernote':
                file = 'mock/user_note.json';
                break;
            case 'channelnote':
                file = 'mock/channel_note.json';
                break;
            default:
                throw new Error('未知的mock类型: ' + type);
        }
        try {
            const resp = await fetch(file);
            if (!resp.ok) {
                throw new Error(`HTTP error! status: ${resp.status}`);
            }
            return await resp.json();
        } catch (error) {
            console.error('加载mock数据失败:', error);
            throw new Error(`加载mock数据失败: ${error.message}`);
        }
    }

    // mock测试按钮
    const testMockBtn = document.getElementById('testMockData');
    if (testMockBtn) {
      testMockBtn.addEventListener('click', async () => {
        const mockTypeSelect = document.getElementById('mockType');
        const type = mockTypeSelect ? mockTypeSelect.value : 'keywordnote';
        updateStatus('开始测试模拟数据...', 'info');
        let mockData;
        try {
          mockData = await loadMockJson(type);
          if (!mockData) {
            throw new Error('加载的mock数据为空');
          }
        } catch (e) {
          updateStatus('加载mock数据失败: ' + e.message, 'error');
          return;
        }
        if (type === 'keywordnote' && mockData && mockData.payload) {
          // 渲染关键词Tab
          renderNotesTable(mockData.payload, 'noteTableBody', 'noteCountInfo');
          // 渲染相关搜索词Tag
          const relatedSearches = mockData.payload.relatedSearches || [];
          const relatedSearchesDiv = document.getElementById('relatedSearches');
          if (relatedSearchesDiv) {
            relatedSearchesDiv.innerHTML = relatedSearches.map(keyword => `<span class="bg-gray-100 dark:bg-gray-700 text-primary text-xs px-3 py-1 rounded-full mr-2 mb-2 inline-block">${keyword}</span>`).join('');
          }
          // 渲染长尾词
          if (mockData.payload.longTailKeywords && Array.isArray(mockData.payload.longTailKeywords) && mockData.payload.longTailKeywords.length > 0) {
            const longTailKeywordsDiv = document.getElementById('longTailKeywords');
            if (longTailKeywordsDiv) {
              const keywords = mockData.payload.longTailKeywords[0]; // 获取第一组长尾关键词
              if (Array.isArray(keywords)) {
                longTailKeywordsDiv.innerHTML = keywords.map(keyword => `
                  <span class="bg-gray-100 dark:bg-gray-700 text-primary text-xs px-3 py-1 rounded-full mr-2 mb-2 inline-block">
                    ${keyword.text || keyword}
                  </span>
                `).join('');
              }
            }
          }
          // 切换到关键词Tab
          document.getElementById('tab-keyword').click();
          // 清空其他区
          renderUserProfileCard(null);
          ['feedTableBody', 'userTableBody'].forEach(id => {
            const tbody = document.getElementById(id);
            if (tbody) tbody.innerHTML = '';
          });
          const commentResult = document.getElementById('commentResult');
          if (commentResult) commentResult.innerHTML = '';
        } else if (type === 'usernote' && mockData && mockData.payload) {
          // 先切换到用户笔记Tab
          document.getElementById('tab-user').click();
          // 渲染用户信息卡片
          if (mockData.payload.userProfileInfo) {
            renderUserProfileCard(mockData.payload.userProfileInfo);
          } else {
            renderUserProfileCard(null);
          }
          // 渲染用户笔记表格
          renderNotesTable(mockData.payload, 'userTableBody', 'userCountInfo');
          // 清空其他区
          ['noteTableBody', 'feedTableBody'].forEach(id => {
            const tbody = document.getElementById(id);
            if (tbody) tbody.innerHTML = '';
          });
          const commentResult = document.getElementById('commentResult');
          if (commentResult) commentResult.innerHTML = '';
          const relatedSearchesDiv = document.getElementById('relatedSearches');
          if (relatedSearchesDiv) relatedSearchesDiv.innerHTML = '';
        } else if (type === 'channelnote' && mockData && mockData.payload) {
          // Render Channel Feed Notes (mock in table mode)
          renderFeedTable(mockData.payload, 'feedTableBody', 'feedCountInfo', 'table');
          // Switch to Channel Feed Tab
          document.getElementById('tab-feed').click();
          // Clear other areas
          renderUserProfileCard(null);
          ['noteTableBody', 'userTableBody'].forEach(id => {
            const tbody = document.getElementById(id);
            if (tbody) tbody.innerHTML = '';
          });
          const commentResult = document.getElementById('commentResult');
          if (commentResult) commentResult.innerHTML = '';
          const relatedSearchesDiv = document.getElementById('relatedSearches');
          if (relatedSearchesDiv) relatedSearchesDiv.innerHTML = '';
        } else if (type === 'comment' && mockData && mockData.payload && mockData.payload.detailPageResult) {
          // 渲染评论Tab
          renderCommentDetail(mockData.payload.detailPageResult);
          // 切换到评论Tab
          document.getElementById('tab-comment').click();
          // 清空笔记区
          ['noteTableBody', 'feedTableBody', 'userTableBody'].forEach(id => {
            const tbody = document.getElementById(id);
            if (tbody) tbody.innerHTML = '';
          });
          renderUserProfileCard(null);
          // 清空相关搜索词
          const relatedSearchesDiv = document.getElementById('relatedSearches');
          if (relatedSearchesDiv) relatedSearchesDiv.innerHTML = '';
        }
        updateStatus('模拟数据测试完成', 'success');
      });
    }

    // 监听 mockType 下拉框变化
    const mockTypeSelect = document.getElementById('mockType');
    if (mockTypeSelect) {
      mockTypeSelect.addEventListener('change', () => {
        // 触发测试模拟数据按钮的点击事件
        const testMockBtn = document.getElementById('testMockData');
        if (testMockBtn) {
          testMockBtn.click();
        }
      });
    }

    // 页面加载完成后初始化
    window.addEventListener('load', () => {
        console.log('Test Page: Page loaded, initializing...');
        
        // 延迟测试消息监听器，给扩展一些加载时间
        setTimeout(testMessageListener, 2000);

        // 注册消息监听器
        window.addEventListener('message', handleExtensionMessage);
    });

    // Tab切换逻辑修复，确保每个Tab点击后只显示对应内容区
    window.addEventListener('DOMContentLoaded', function() {
      function showTab(tabId) {
        document.querySelectorAll('.hs-tab-content').forEach(el => el.classList.add('hidden'));
        document.getElementById(tabId).classList.remove('hidden');
        document.querySelectorAll('[data-hs-tab]').forEach(btn => {
          if (btn.getAttribute('data-hs-tab') === '#' + tabId) {
            btn.classList.add('bg-primary', 'text-white');
            btn.setAttribute('aria-selected', 'true');
          } else {
            btn.classList.remove('bg-primary', 'text-white');
            btn.setAttribute('aria-selected', 'false');
          }
        });
      }
      ['tab-keyword','tab-feed','tab-user','tab-comment'].forEach(tabBtnId => {
        const btn = document.getElementById(tabBtnId);
        if(btn){
          btn.addEventListener('click', function(){
            const tabId = btn.getAttribute('data-hs-tab').replace('#','');
            showTab(tabId);
          });
        }
      });
      showTab('tab-panel-keyword');
    });

    // 渲染笔记表格（关键词、用户笔记Tab通用，含操作列）
    function renderNotesTable(data, tableBodyId, countInfoId) {
      const tbody = document.getElementById(tableBodyId);
      tbody.innerHTML = '';
      if (!data || !data.notes || !Array.isArray(data.notes)) return;

      // 渲染长尾词
      if (data.longTailKeywords && Array.isArray(data.longTailKeywords) && data.longTailKeywords.length > 0) {
        const longTailKeywordsDiv = document.getElementById('longTailKeywords');
        if (longTailKeywordsDiv) {
          const keywords = data.longTailKeywords[0]; // 获取第一组长尾关键词
          if (Array.isArray(keywords)) {
            longTailKeywordsDiv.innerHTML = keywords.map(keyword => `
              <span class="bg-gray-100 dark:bg-gray-700 text-primary text-xs px-3 py-1 rounded-full mr-2 mb-2 inline-block">
                ${keyword.text || keyword}
              </span>
            `).join('');
          }
        }
      }

      data.notes.forEach(note => {
        const tr = document.createElement('tr');
        tr.className = 'hover:bg-gray-50 dark:hover:bg-gray-800 transition-all duration-200';
        tr.innerHTML = `
          <td class="px-4 py-2 max-w-xs truncate">
            <a href="${note.url || '#'}" target="_blank" class="text-primary hover:underline">${note.title || 'N/A'}</a>
          </td>
          <td class="px-4 py-2 flex items-center gap-2">
            <img src="${note.authorAvatarUrl || ''}" alt="" class="w-6 h-6 rounded-full object-cover" loading="lazy">
            <span>${note.author || 'N/A'}</span>
          </td>
          <td class="px-4 py-2">${note.likeCount || 0}</td>
          <td class="px-4 py-2">${note.publishTime || 'N/A'}</td>
          <td class="px-4 py-2">
            <a href="${note.url || '#'}" target="_blank" class="text-blue-500 hover:underline"><i class="fa-solid fa-arrow-up-right-from-square"></i> 查看</a>
          </td>
        `;
        tbody.appendChild(tr);
      });
      if (countInfoId) {
        document.getElementById(countInfoId).textContent = `共 ${data.notes.length} 条`;
      }
    }

    // 测试用户笔记提取按钮点击事件
    const testUserBtn = document.getElementById('testProfileExtraction');
    if (testUserBtn) {
      testUserBtn.addEventListener('click', async () => {
        const userUrlInput = document.getElementById('userUrl');
        const url = userUrlInput ? userUrlInput.value : '';
        if (!url) {
          updateStatus('请输入用户主页URL');
          return;
        }

        // 从URL中提取用户ID
        let userId;
        try {
          const urlObj = new URL(url);
          // 处理两种可能的URL格式:
          // 1. /user/profile/{userId}
          // 2. /user/profile/{userId}?channel_type=...
          const pathParts = urlObj.pathname.split('/');
          if (pathParts.length >= 4 && pathParts[1] === 'user' && pathParts[2] === 'profile') {
            userId = pathParts[3];
          } else {
            throw new Error('无效的用户主页URL格式');
          }
        } catch (error) {
          updateStatus('URL格式错误: ' + error.message);
          return;
        }

        updateStatus('开始提取用户笔记数据...');
        try {
          const response = await sendMessageToExtension({
            action: 'getUserProfile',
            userId: userId,
            targetCount: config.targetNoteCount
          });
          if (response && response.payload) {
            if (response.payload.userProfileInfo) {
              renderUserProfileCard(response.payload.userProfileInfo);
            }
            renderNotesTable(response.payload, 'userTableBody', 'userCountInfo');
          }
          updateStatus('用户笔记数据提取完成');
        } catch (error) {
          updateStatus('提取失败: ' + error.message);
        }
      });
    }

    // 测试评论提取按钮点击事件
    const testCommentBtn = document.getElementById('testCommentExtraction');
    if (testCommentBtn) {
      testCommentBtn.addEventListener('click', async () => {
        const noteUrlInput = document.getElementById('noteUrl');
        const url = noteUrlInput ? noteUrlInput.value : '';
        if (!url) {
          updateStatus('请输入笔记URL');
          return;
        }
        updateStatus('开始提取评论数据...');
        try {
          const response = await sendMessageToExtension({
            action: 'getNoteDetail',
            noteUrl: url,
            targetCommentCount: config.targetCommentCount
          });
          const commentResult = document.getElementById('commentResult');
          if (commentResult && response && response.detailPageResult) {
            renderCommentDetail(response.detailPageResult);
          }
          updateStatus('评论数据提取完成');
        } catch (error) {
          updateStatus('提取失败: ' + error.message);
        }
      });
    }

    // 测试消息监听器是否正常工作
    async function testMessageListener() {
        try {
            console.log('Test Page: Testing message listener...');
            const response = await sendMessageToExtension({
                type: 'test',
                data: { test: 'data' }
            });
            console.log('Test Page: Received test response:', response);
        } catch (error) {
            console.error('Test Page: Message test failed:', error);
        }
    }

    // 格式化 JSON 显示
    function formatJSON(json) {
        if (typeof json === 'string') {
            try {
                json = JSON.parse(json);
            } catch (e) {
                return json;
            }
        }
        
        const formatted = JSON.stringify(json, null, 2);
        return formatted
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                let cls = 'json-number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'json-key';
                    } else {
                        cls = 'json-string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'json-boolean';
                } else if (/null/.test(match)) {
                    cls = 'json-null';
                }
                return '<span class="' + cls + '">' + match + '</span>';
            });
    }

    // 更新状态显示函数
    function updateStatus(message, type = 'info') {
        const status = document.getElementById('status');
        const logResult = document.getElementById('logResult');
        const timestamp = new Date().toLocaleTimeString();
        
        // 更新状态显示
        status.textContent = message;
        status.className = 'status ' + type;
        
        // 更新日志
        const logEntry = document.createElement('div');
        logEntry.className = 'data-card';
        logEntry.innerHTML = `
            <div class="status ${type}">
                <span class="timestamp">[${timestamp}]</span>
                <span class="message">${message}</span>
            </div>
        `;
        logResult.insertBefore(logEntry, logResult.firstChild);
    }

    // 更新结果显示函数
    function updateResult(elementId, data, title = '') {
        const element = document.getElementById(elementId);
        if (!element) return;

        const formattedData = formatJSON(data);
        let keywordsHtml = '';

        // 处理相关搜索词数据
        if (data.relatedSearches && Array.isArray(data.relatedSearches)) {
            keywordsHtml += `
                <div class="keywords-section">
                    <div class="keywords-title">相关搜索词</div>
                    <div class="keywords-list">
                        ${data.relatedSearches.map(keyword => `
                            <span class="keyword-tag">
                                ${keyword}
                            </span>
                        `).join('')}
                    </div>
                </div>
            `;
        }

        // 处理长尾关键词数据
        if (data.longTailKeywords && Array.isArray(data.longTailKeywords) && data.longTailKeywords.length > 0) {
            const longTailKeywords = data.longTailKeywords[0]; // 获取第一组长尾关键词
            if (Array.isArray(longTailKeywords)) {
                keywordsHtml += `
                    <div class="keywords-section">
                        <div class="keywords-title">长尾关键词</div>
                        <div class="keywords-list">
                            ${longTailKeywords.map(keyword => `
                                <span class="keyword-tag">
                                    ${keyword.text || keyword}
                                </span>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
        }

        element.innerHTML = `
            <div class="data-card">
                ${title ? `<h3>${title}</h3>` : ''}
                ${keywordsHtml}
                <pre class="json-content">${formattedData}</pre>
            </div>
        `;
    }

    // 修改消息处理函数中的数据显示部分
    function handleExtensionMessage(event) {
        // 1. 验证消息来源
        if (event.source !== window ||
            event.origin !== window.location.origin ||
            !event.data ||
            event.data.source !== 'xiaohong-extension-bridge') {
            console.log('Ignoring message from different origin or invalid source:', event.origin);
            return;
        }

        console.log('Test Page: Received message from extension:', event.data);

        // 2. 根据消息类型处理数据
        const payload = event.data.payload;
        if (!payload) {
            console.warn('Received message without payload');
            return;
        }

        // Helper function to clear all main display areas
        function clearAllDisplayAreas() {
          renderUserProfileCard(null); // Clear user profile card
          ['noteTableBody', 'feedTableBody', 'userTableBody'].forEach(id => {
            const tbody = document.getElementById(id);
            if (tbody) tbody.innerHTML = '';
            // Restore table styles if they were changed to grid
            if (tbody && tbody.parentElement) {
                tbody.parentElement.classList.remove('grid', 'grid-cols-1', 'md:grid-cols-2', 'gap-4', 'bg-transparent');
                tbody.parentElement.classList.add('overflow-x-auto');
            }
          });
          // Also clear the card view for channel feed
          const feedCardView = document.getElementById('feedCardView');
          if (feedCardView) feedCardView.innerHTML = '';

          const commentResult = document.getElementById('commentResult');
          if (commentResult) commentResult.innerHTML = '';
          const relatedSearchesDiv = document.getElementById('relatedSearches');
          if (relatedSearchesDiv) relatedSearchesDiv.innerHTML = '';
        }

        // 3. 处理不同类型的消息
        switch (event.data.type) {
            case 'extractionResult':
                updateStatus('提取完成', 'success');
                clearAllDisplayAreas(); // Clear previous results first

                if (payload.pageType === 'explore_feed' && payload.notes && Array.isArray(payload.notes) && payload.notes.length > 0) {
                    // Render Channel Feed Notes (card style for real data)
                    renderFeedTable(payload, 'feedTableBody', 'feedCountInfo', 'both'); // Render both table and cards for real data
                    document.getElementById('tab-feed').click();
                } else if (payload.pageType === 'search_result' && payload.notes && Array.isArray(payload.notes) && payload.notes.length > 0) {
                    // Render Search Result Notes
                    renderNotesTable(payload, 'noteTableBody', 'noteCountInfo');
                    // Render related searches
                    const relatedSearches = payload.relatedSearches || [];
                    const relatedSearchesDiv = document.getElementById('relatedSearches');
                    if (relatedSearchesDiv) {
                      relatedSearchesDiv.innerHTML = relatedSearches.map(keyword => `<span class="bg-gray-100 dark:bg-gray-700 text-primary text-xs px-3 py-1 rounded-full mr-2 mb-2 inline-block">${keyword}</span>`).join('');
                    }
                    // Render long tail keywords
                    const longTailKeywordsDiv = document.getElementById('longTailKeywords');
                    if (longTailKeywordsDiv && payload.longTailKeywords && Array.isArray(payload.longTailKeywords) && payload.longTailKeywords.length > 0) {
                      const keywords = payload.longTailKeywords;
                      if (Array.isArray(keywords)) {
                        longTailKeywordsDiv.innerHTML = keywords.map(keyword => `
                          <span class="bg-gray-100 dark:bg-gray-700 text-primary text-xs px-3 py-1 rounded-full mr-2 mb-2 inline-block">
                            ${keyword.text || keyword}
                          </span>
                        `).join('');
                      }
                    }
                    document.getElementById('tab-keyword').click();
                } else if (payload.userProfileInfo && payload.notes && Array.isArray(payload.notes) && payload.notes.length > 0) {
                    // Render User Notes
                    renderUserProfileCard(payload.userProfileInfo);
                    renderNotesTable(payload, 'userTableBody', 'userCountInfo');
                    document.getElementById('tab-user').click();
                } else if (payload.detailPageResult) {
                    // Render Comment Details
                    renderCommentDetail(payload.detailPageResult);
                    document.getElementById('tab-comment').click();
                } else {
                    // Handle cases with no data or unknown payload structure
                    updateStatus('提取完成，但未找到可渲染的数据', 'warning');
                }
                break;

            case 'detailResult': // Assuming this is an alternative for comment details if extractionResult isn't used
                updateStatus('笔记详情提取完成', 'success');
                 clearAllDisplayAreas(); // Clear previous results first
                if (payload.detailData) {
                    renderCommentDetail(payload.detailData);
                    document.getElementById('tab-comment').click();
                } else {
                    updateStatus('提取完成，但未找到笔记详情数据', 'warning');
                }
                break;

            case 'extractionError':
                updateStatus(`提取错误: ${payload.error || '未知错误'}`, 'error');
                break;

            case 'extractionProgress':
                updateStatus(`提取进度: ${payload.progress}%`, 'info');
                // Optional: Update a progress bar or indicator on the page
                break;

            default:
                console.warn('Received unknown message type:', event.data.type);
        }
    }

    // 渲染评论区（评论Mock专用）
    function renderCommentDetail(detailPageResult) {
      const commentResult = document.getElementById('commentResult');
      if (!commentResult) return;
      if (!detailPageResult || !Array.isArray(detailPageResult.comments)) {
        commentResult.innerHTML = '<div class="text-gray-400">暂无评论数据</div>';
        return;
      }
      // 顶部笔记信息
      const author = detailPageResult.authorInfo || {};
      const tags = (detailPageResult.tags || []).map(tag => `<span class='bg-gray-100 dark:bg-gray-700 text-primary text-xs px-2 py-0.5 rounded mr-1'>#${tag}</span>`).join('');
      const images = (detailPageResult.imageUrls || []).map(url => `<img src='${url}' class='w-32 h-32 object-cover rounded-lg mr-3 mb-3 border shadow-sm hover:scale-105 transition-transform duration-200' loading='lazy'>`).join('');
      
      // 处理视频内容
      let videoContent = '';
      if (detailPageResult.videoUrls && detailPageResult.videoUrls.length > 0) {
        const videoUrl = detailPageResult.videoUrls[0];
        const posterUrl = detailPageResult.videoPosterUrl || '';
        videoContent = `
          <div class="relative w-32 h-32 rounded-lg mr-3 mb-3 border shadow-sm overflow-hidden hover:scale-105 transition-transform duration-200">
            <video 
              src="${videoUrl}" 
              poster="${posterUrl}"
              class="w-full h-full object-cover"
              controls
              preload="none"
            ></video>
          </div>
        `;
      }

      const noteHeader = `
        <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-6 mb-6">
          <div class="flex items-center gap-3 mb-3">
            <img src="${author.avatarUrl || ''}" class="w-12 h-12 rounded-full object-cover border-2 border-primary" loading="lazy">
            <div>
              <div class="font-bold text-gray-800 dark:text-gray-200">${author.nickname || ''}</div>
              <div class="text-xs text-gray-400">${detailPageResult.publishedInfoText || ''}</div>
            </div>
          </div>
          <div class="font-semibold text-lg mb-2 text-gray-900 dark:text-gray-100">${detailPageResult.title || ''}</div>
          <div class="text-gray-700 dark:text-gray-300 mb-3 whitespace-pre-line">${detailPageResult.content || ''}</div>
          <div class="mb-3">${tags}</div>
          <div class="flex flex-wrap gap-2">${images}${videoContent}</div>
          <div class="flex gap-6 text-sm text-gray-500 mt-3">
            <span><i class="fa-regular fa-heart"></i> ${detailPageResult.interactionCounts?.likes || 0}</span>
            <span><i class="fa-regular fa-comment"></i> ${detailPageResult.interactionCounts?.comments || 0}</span>
            <span><i class="fa-regular fa-bookmark"></i> ${detailPageResult.interactionCounts?.collects || 0}</span>
          </div>
        </div>
      `;
      // 评论列表
      function renderReplies(replies) {
        if (!replies || !replies.length) return '';
        return replies.map(reply => `
          <div class='flex gap-2 items-start mt-2 ml-10 border-l-2 border-gray-200 dark:border-gray-700 pl-3'>
            <img src='${reply.avatar || ''}' class='w-7 h-7 rounded-full object-cover mt-1' loading='lazy'>
            <div class='flex-1'>
              <div class='flex items-center gap-2 mb-0.5'>
                <span class='font-semibold text-gray-700 dark:text-gray-200 text-sm'>${reply.author || '匿名'}</span>
                <span class='text-xs text-gray-400'>${reply.timestamp || ''}</span>
                ${reply.ipLocation ? `<span class='text-xs bg-gray-100 dark:bg-gray-700 px-1 rounded'>${reply.ipLocation}</span>` : ''}
              </div>
              <div class='text-gray-700 dark:text-gray-300 text-sm'>${reply.text || ''}</div>
            </div>
          </div>
        `).join('');
      }
      const commentList = detailPageResult.comments.map(comment => `
        <div class="flex gap-3 items-start py-4 border-b border-gray-100 dark:border-gray-800">
          <img src="${comment.avatar || ''}" class="w-9 h-9 rounded-full object-cover mt-1" loading="lazy">
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-1">
              <span class="font-semibold text-gray-800 dark:text-gray-200">${comment.author || '匿名'}</span>
              <span class="text-xs text-gray-400">${comment.timestamp || ''}</span>
              ${comment.ipLocation ? `<span class='text-xs bg-gray-100 dark:bg-gray-700 px-1 rounded'>${comment.ipLocation}</span>` : ''}
              ${comment.isAuthor ? `<span class='text-xs text-primary border border-primary px-1 rounded ml-1'>作者</span>` : ''}
            </div>
            <div class="text-gray-700 dark:text-gray-300 mb-1">${comment.text || ''}</div>
            <div class="flex gap-4 text-xs text-gray-400 mb-1">
              <span><i class="fa-regular fa-thumbs-up"></i> ${comment.likes || 0}</span>
              <span><i class="fa-regular fa-comment"></i> ${comment.replyCount || 0}</span>
            </div>
            ${renderReplies(comment.replies)}
          </div>
        </div>
      `).join('');
      commentResult.innerHTML = noteHeader + `<div class='mb-2 font-bold text-gray-700 dark:text-gray-200 text-base'>全部评论</div>` + commentList;
    }

    // 添加收起/展开详细提示语的逻辑
    const toggleDetailedTipsBtn = document.getElementById('toggleDetailedTips');
    const detailedTipsContent = document.getElementById('detailedTipsContent');

    if (toggleDetailedTipsBtn && detailedTipsContent) {
      toggleDetailedTipsBtn.addEventListener('click', () => {
        const isHidden = detailedTipsContent.classList.toggle('hidden');
        toggleDetailedTipsBtn.textContent = isHidden ? '展开' : '收起';
      });
    }
  </script>
</body>
</html>